package com.ktjiaoyu.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjiaoyu.server.mapper.EmployeeMapper;
import com.ktjiaoyu.server.pojo.Employee;
import com.ktjiaoyu.server.pojo.RespBean;
import com.ktjiaoyu.server.service.IEmployeeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jieGe
 * @since 2022-02-10
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {
    @Resource
    private EmployeeMapper employeeMapper;

    // 分页显示员工基本资料列表, 并按员工名模糊查询及政治面貌、部门、入职时间查询
    @Override
    public IPage<Employee> selectByPage(Page<Employee> page, String query, String sort, Integer politicsId, Integer deptId, String beginTime, String endTime) {
        return employeeMapper.selectByPage(page, query, sort, politicsId, deptId, beginTime, endTime);
    }

    // 获取新增员工基本资料时所需要的工号，原理是取workid列的最大值再 + 1
    @Override
    public RespBean maxWorkID() {
        // select max(workID) from t_department
        List<Map<String, Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workID)"));
        String workID = String.format("%08d", Integer.parseInt(maps.get(0).get("max(workID)").toString()) + 1);
        return RespBean.success(null, workID);
    }

    /**
     * 新增员工基本资料
     *
     * @return
     */
    @Override
    public RespBean addEmp(Employee employee) {
        // 新增员工时需要对合同期限进行处理，合同期限需要保存两位小数
        // 1、获取合同开始时间
        LocalDate beginContract = employee.getBeginContract();
        // 2、获取合同结束时间
        LocalDate endContract = employee.getEndContract();
        // 3、计算开始时间到结束时间之间的间隔天数
        long days = beginContract.until(endContract, ChronoUnit.DAYS);
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days / 365.00)));
        if (employeeMapper.insert(employee) > 0) {
            return RespBean.success("添加成功!");
        }
        return RespBean.error("添加失败");
    }

}
